#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>

#define MAX_LEN   128//指令的最大长度
#define CMD_NUM   64//指令可包含最大参数个数

int main()
{
  char command[MAX_LEN] = {0};
  while (1)
  {
    char* argv[CMD_NUM] = {NULL};
    command[0] = 0;
    //1.打印提示符
    printf("[clx@VM-20-6-centos my_shell]$");
    fflush(stdout); //刷新缓冲区
    //2.接收命令行
    fgets(command, MAX_LEN, stdin);
    command[strlen(command) - 1] = 0; //"ls -a\n" \n的下标为5 字符串长度为6
    //3.解析命令行
    const char* sep = " ";
    argv[0] = strtok(command, sep);
    size_t i = 1;
    while (argv[i] = strtok(NULL, sep)) {i++;}
    //4.检测命令是否是shell本身执行的，内建命令
    if (strcmp(argv[0], "cd") == 0)
    {
      if (argv[1] != NULL)
      {
        chdir(argv[1]);
        continue;
      }
    }
    //5.创建子进程执行第三方命令
    if (fork() == 0)
    {
      //child
      execvp(argv[0], argv);
      exit(1);
    }
    //父进程进行夯等待
    waitpid(-1, NULL, 0);
  }
  return 0;
}
